const webSocketAPI = (wss, app) => wss.on('connection', (ws, req) => {
  let time = null;
  let list = [
    {
      amount: 123,
      caseCount: 364,
      year: 2020
    },
    {
      amount: 64,
      caseCount: 123,
      year: 2021
    },
    {
      amount: 238,
      caseCount: 468,
      year: 2022
    },
    {
      amount: 342,
      caseCount: 894,
      year: 754
    },
    {
      amount: 332,
      caseCount: 443,
      year: 2024
    },
  ]


  ws.on('message', async message => {
    // 解析URL获取查询参数
    const url = new URL(req.url, `http://${req.headers.host}`);
    const params = new URLSearchParams(url.search);
    const token = params.get('token');
    if (!token) {
      ws.send('缺少token参数，连接被拒绝')
      return
    }
    console.log("用户token：", token)

    console.log(`服务端接收到客户端的消息：${message}`)

    // 模拟处理消息，例如将字符串转换为大写

    time = setInterval(() => {
      console.log("定时发送数据")
      list = list.map(item => ({
        amount: item.amount + 1,
        caseCount: item.caseCount + 1,
        year: 2020
      }))

      const data = JSON.stringify({
        list: list,
        code: 200,
        msg: "成功",
        time: new Date().getTime()
      })



      ws.send(data) // 发送的消息需要是一个字符串
    }, 5000)


    // ws.send(`服务端说：${message}`) // 发送的消息需要是一个字符串
  })

  ws.on('close', () => {
    console.log('客户端关闭连接')
  })
})

module.exports = webSocketAPI